package city.spring.modules.oldman.controller;

import city.spring.modules.oldman.entity.ComplaintReceiverExtEntity;
import city.spring.modules.oldman.repository.ComplaintReceiverExtRepository;
import city.spring.modules.oldman.service.ComplaintReceiverExtService;
import city.spring.modules.oldman.vo.ComplaintReceiverExtVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：投诉-受理人联系表
 *
 * @author pxm
 * @date 2020-07-20 16:56:39
 */
@RestController
@RequestMapping("/complaint_receiver_ext/{complaintId}/receiver")
public class ComplaintReceiverExtController extends ApiController {
    private final ComplaintReceiverExtService complaintReceiverExtService;
    private final ComplaintReceiverExtRepository complaintReceiverExtRepository;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<ComplaintReceiverExtEntity, ?>> entityOrderFields;

    public ComplaintReceiverExtController(ComplaintReceiverExtService complaintReceiverExtService, ComplaintReceiverExtRepository complaintReceiverExtRepository) {
        this.complaintReceiverExtService = complaintReceiverExtService;
        this.complaintReceiverExtRepository = complaintReceiverExtRepository;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(ComplaintReceiverExtEntity::getId);
        entityOrderFields.add(ComplaintReceiverExtEntity::getComplaintId);
        entityOrderFields.add(ComplaintReceiverExtEntity::getReceiverId);
    }

    @ModelAttribute
    public void getComplaintId(@PathVariable String complaintId) {
        if (complaintId == null) {
            throw new RuntimeException("投诉记录ID必须不为空");
        }
    }

    /**
     * 获取投诉记录所有受理人员列表
     *
     * @param complaintId 投诉记录ID
     */
    @GetMapping
    public Object list(@PathVariable String complaintId) {
        return success(complaintReceiverExtRepository.getComplaintReceivers(complaintId));
    }

    /**
     * 给投诉记录添加多个受理人员信息
     *
     * @param complaintId 投诉记录ID
     * @param receivers   所添加的人员信息列表
     * @return
     */
    @PostMapping
    public Object addAll(@PathVariable String complaintId, @RequestBody List<ComplaintReceiverExtEntity> receivers) {
        // 查出已有的数据
        List<ComplaintReceiverExtVO> dbReceivers = complaintReceiverExtRepository.getComplaintReceivers(complaintId);
        // 数据库已经存在的列表
        Set<String> dbReceiverIdsSet = dbReceivers.stream()
                .map(ComplaintReceiverExtEntity::getReceiverId)
                .collect(Collectors.toSet());
        // 过滤掉已经存在数据库的数据
        List<ComplaintReceiverExtEntity> needSaveReceivers = receivers.stream()
                .filter(item -> {
                    item.setComplaintId(complaintId);
                    String receiverId = item.getReceiverId();
                    // 过滤出不存在数据库中的数据
                    return receiverId != null && !dbReceiverIdsSet.contains(receiverId);
                }).collect(Collectors.toList());
        if (!needSaveReceivers.isEmpty()) {
            complaintReceiverExtService.saveBatch(needSaveReceivers);
        }

        return success(null);
    }

    /**
     * 获取投诉的一个人员信息
     *
     * @param complaintId 投诉记录ID
     * @param extId       关联ID
     * @return
     */
    @GetMapping("{extId}")
    public Object getInfo(@PathVariable String complaintId, @PathVariable String extId) {
        return success(complaintReceiverExtRepository.getComplaintReceiver(complaintId, extId));
    }

    /**
     * 修改一个投诉关联的人员信息
     *
     * @param complaintId 投诉记录ID
     * @param extId       关联ID
     * @param extEntity   接收的数据
     * @return
     */
    @PutMapping("{extId}")
    public Object update(@PathVariable String complaintId, @PathVariable String extId, @RequestBody ComplaintReceiverExtEntity extEntity) {
        extEntity.setId(extId);
        extEntity.setComplaintId(complaintId);
        complaintReceiverExtService.updateComplaintReceiverExt(extEntity);
        return success(null);
    }

    /**
     * 删除一个 <strong>记录的关联人员信息</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        complaintReceiverExtService.deleteComplaintReceiverExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>投诉的关联人员信息</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        complaintReceiverExtService.deleteComplaintReceiverExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<ComplaintReceiverExtEntity> buildLambdaQuery(ComplaintReceiverExtEntity entity) {
        LambdaQueryChainWrapper<ComplaintReceiverExtEntity> lambdaQuery = complaintReceiverExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), ComplaintReceiverExtEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getComplaintId()), ComplaintReceiverExtEntity::getComplaintId, entity.getComplaintId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getReceiverId()), ComplaintReceiverExtEntity::getReceiverId, entity.getReceiverId());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<ComplaintReceiverExtEntity> buildQuery(ComplaintReceiverExtEntity entity) {
        QueryWrapper<ComplaintReceiverExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getComplaintId()), "complaint_id", entity.getComplaintId());
        wrapper.like(StringUtils.isNotBlank(entity.getReceiverId()), "receiver_id", entity.getReceiverId());
        return wrapper;
    }

}
